﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SY.BasicData.Api.Write.Basic.Applications.Command;
using SY.BasicData.Domain.Base;
using SY.BasicData.Domain.Basic;
using SY.BasicData.Domain.DeepProcessing;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;

namespace SY.BasicData.Api.Write.Basic.Applications.CommandHandler
{
    public class UpdateBasicCommandHandler : IRequestHandler<UpdateBasicCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BasicModel> basicRepository;
        private readonly IBaseRepository<DeepProcessingCompanyModel> deepprocessRepository;
        private readonly IMapper mapper;

        public UpdateBasicCommandHandler(IBaseRepository<BasicModel> basicRepository, IBaseRepository<DeepProcessingCompanyModel> deepprocessRepository, IMapper mapper)
        {
            this.basicRepository = basicRepository;
            this.deepprocessRepository = deepprocessRepository;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(UpdateBasicCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "修改成功";
            var batchExists = await basicRepository.GetAll().Where(x => x.Id == request.Id && x.Batch == request.Batch && x.IsDeleted == false).AnyAsync();

            if (batchExists)
            {
                result.Message = "存在更新的同批次数据，请修改最新记录";
                result.Code = ApiEnum.Fail;
                return result;
            }
            // 获取要修改的基础信息
            var basic = await basicRepository.GetAll().FirstOrDefaultAsync(x => !x.IsDeleted && x.Id == request.Id);
            if (basic == null)
            {
                result.Message = "找不到编号";
                result.Code = ApiEnum.Fail;
                return result;
            }

            // 只更新最新的一条深加工企业记录
            if (!string.IsNullOrEmpty(request.License))
            {
                var latestDeepProcessCompany = await deepprocessRepository.GetAll().Where(c => c.Batch == request.Batch && !c.IsDeleted).OrderByDescending(c => c.Id).FirstOrDefaultAsync();

                if (latestDeepProcessCompany != null)
                {
                    latestDeepProcessCompany.LicenseNum = request.License;
                    await deepprocessRepository.Update(latestDeepProcessCompany);
                }
            }

            // 直接更新已跟踪的实体，而不是创建新实体
            mapper.Map(request, basic); // 使用Map的第二个重载来更新现有实体
            //BasicModel baseModel = mapper.Map<BasicModel>(request);
            basic.Updator = request.Updator;
            basic.UpdatorDate = DateTime.Now;
            var res = await basicRepository.Update(basic);
            result.Code = res > 0 ? ApiEnum.Success : ApiEnum.Fail;
            result.Message = res > 0 ? "修改基本信息成功" : "修改基本信息失败";
            result.Data = res;
            return result;
        }
    }
}
